const app = getApp()
Page({
  data: {
    loading: true,
    showKeyboard: false,
    store_id: 0,
    code_id: 0,
    quan_id:0, //商圈ID
    page: 0,
    isInput:false,
    input_money:0,    //基础价
    discount_money: 0, //已优惠多少钱
    price: 0,  //小计
    amount: 0, //付款金额
    coupon_price: 0,
    coupon_user: [],  //客户赠品礼包
    coupon_user_id: 0,
    coupon_user_key: 0,
    coupon_count:0,
    coupon: [],
    coupon_id: [],
    coupon_ids: [], //已选赠品ID
    checkbox: []
  },
  onLoad: function (options) {
    var store_id = 0,code_id = 0;
    if (app.util().isNull(options.q)) {
      store_id = options.store_id;
      if (app.util().isNull(store_id)) {
        app.wxAlert('未找到付款好店');
      }
    } else {
      var url = decodeURIComponent(options.q);
          code_id = url.slice(-12);
      if (app.util().isNull(code_id)) {
        app.wxAlert('请重新扫码');
      }
    }
    this.setData({
      store_id: store_id,
      code_id: code_id,
    });
  },
  //监听页面加载
  onShow: function () {
    app.isLogin(() =>{
      this.getStore();
    });
  },
  //底部加载
  onReachBottom: function () {
    this.setData({
      loading: true,
    });
    this.getCoupon();
  },
  //读取商品
  getStore: function () {
    var param = {
      signkey: app.util().getRandom(12),
      store_id: this.data.store_id,
      code_id: this.data.code_id
    }
    app.api().Get('api/v4/allwin/payment/index',param,(result) =>{
      this.setData({
        store: result.data,
        store_id:result.data.id
      });
      this.data.quan_id = result.data.quan_id;
      this.getStoreCoupon();
      this.getCoupon();
    })
  },
  //读取用户已领赠品
  getStoreCoupon: function () {
    var param = {
      signkey:app.util().getRandom(12),
      price: parseFloat(this.data.input_money),
      store_id:this.data.store_id
    }
    app.api().Get('api/v4/allwin/payment/userCoupon',param,(rel) => {
      if(rel.code == 200){
        this.setData({
          coupon_user_id:param.price > 0 ? rel.data[0].id : 0,
          coupon_user:rel.data,
        })
      }else{
        this.setData({
          coupon_user_id:0,
          coupon_user:[],
        })
      }
      this.amount();
    });
  },
  //根据输入金额大小请求平台
  getCoupon: function () {
    if (this.data.loading) {
      if (this.data.page >= 1){
        var coupon = this.data.coupon,checkbox = this.data.checkbox,coupon_id = this.data.coupon_id;
      }else{
        var coupon = [],checkbox = [],coupon_id = [];
      }
      var param = {
        signkey:app.util().getRandom(12),
        page:this.data.page + 1,
        store_id:this.data.store_id,
        price:app.util().isNull(this.data.input_money) ? 0 : parseFloat(this.data.input_money),
        quan_id:this.data.quan_id
      }
      app.api().Get('api/v4/allwin/payment/coupon',param, (rel) =>{
        if(rel.code == 200){
          for (let i in rel.data){
            coupon.push(rel.data[i]);
            coupon_id.push(0);
            checkbox.push(false);
          }
          //初始化原来设置
          this.setData({
            checkbox: checkbox,
            coupon: coupon,
          })
          if (this.data.page == 1) {
            this.data.coupon_price = 0
          }
          this.data.coupon_id = coupon_id
          this.data.page      = param.page
          this.coupon_count();
        }
      });
    }
    this.setData({
      loading:false
    })
  },
  //选择已有赠品
  selectCouponUser: function (event) {
    if (this.data.input_money <= 0) {
      app.wxAlert('请输入付款金额');
      return;
    } 
    this.setData({
      coupon_user_id:event.currentTarget.dataset.id,
    })
    this.data.coupon_user_key = event.currentTarget.dataset.key
    this.amount() //计算价格
  },
  //选择新领取赠品
  onCheckbox(event) {
    var id  = event.currentTarget.dataset.id;
    var key = event.currentTarget.dataset.key
    var checkbox  = !this.data.checkbox[key]; //选择赠品KEY
    if ( this.data.input_money <= 0) {
      app.wxAlert('请输入付款金额');
      return;
    } 
    if (checkbox == true) {
      if (this.data.coupon_count >= 2) {
        app.wxAlert('仅允许选 2 个赠品');
        return;
      } 
    }
    var coupon = this.data.coupon; //所有赠品        
    //选择
    var checkbox_array = "checkbox[" + key + "]";
    this.setData({
      [checkbox_array]: checkbox,
    });
    //计算赠品价格
    var coupon_price = parseFloat(this.data.coupon_price); 
    if (checkbox == true) {
      coupon_price = coupon_price + parseFloat(coupon[key].pay_price);
    }else{
      coupon_price = coupon_price - parseFloat(coupon[key].pay_price);
    }
    this.data.coupon_price = coupon_price
    //已选择赠品ID
    var coupon_id = this.data.coupon_id;
        coupon_id[key] = checkbox ? id : 0; 
    this.data.coupon_id    = coupon_id
    this.coupon_count(); //
    this.amount() //计算价格
  },
  //统计已选优惠券
  coupon_count: function () {
    var coupon = this.data.coupon_id;
    var len = [];
    var j = 0;
    for (var i in coupon) {
      if (coupon[i] != 0) {
        len[j] = coupon[i];
        j++
      }
    }
    this.data.coupon_ids = len;  //仅保留已选择产品ID提交给后端
    this.setData({
      coupon_count:len.length
    })
  },
  //价格计算方式
  amount:function () {
    var coupon_user  = this.data.coupon_user,coupon_user_key = this.data.coupon_user_key;
    //计算使用优惠券有的价格
    var discount_money = 0; //已优惠有价格
    if (this.data.coupon_user_id){
      if (coupon_user[coupon_user_key].types == 1) {
        //折扣
        var discount = parseInt(coupon_user[coupon_user_key].discount) / 10;
        var discount_money = this.data.input_money - this.data.input_money * discount;  //优惠了多少钱
        if (discount_money >= coupon_user[coupon_user_key].user_size) {
          discount_money = parseFloat(coupon_user[coupon_user_key].user_size);
        }
      } else {
        //抵扣
        if (parseInt(coupon_user[coupon_user_key].price) >= parseInt(coupon_user[coupon_user_key].user_size)) {
          discount_money = parseFloat(coupon_user[coupon_user_key].user_size);
        } else {
          discount_money = parseFloat(coupon_user[coupon_user_key].price);
        }
      }
    }
    //判断优惠后价格禁止小于0
    if (parseFloat(this.data.input_money) <= 0) {
      this.setData({
        input_money: 0
      })
    }
    var price = parseFloat(this.data.input_money - discount_money);
    if (price <= 0) {
      price = 0;
    }
    var amount = parseFloat(this.data.coupon_price + price)
    if (amount <= 0){
      amount = 0;
    }
    this.setData({
      discount_money: discount_money.toFixed(2),
      price: price.toFixed(2),
      amount: amount.toFixed(2)
    })
  },
  /**
   * 提交付款中
   */
  doSubmitPay:function () {
    if (this.data.input_money == 0){
      app.wxAlert('请输入付款金额');
    }else{
      if (this.data.coupon_user.length > 0) {
        if (this.data.coupon_user_id == 0) {
          wx.showModal({
            content:'你还有赠品未使用？',
            cancelText:'不使用',confirmText	:'去使用',
            success:(res) => {
              if (res.cancel) {
                this.isCoupon();
              }
            }
          })
        }else{
          this.isCoupon();
        }
      } else {
        this.isCoupon();
      }
    }
  },
  //判断是否选择了赠品
  isCoupon: function () {
    if (this.data.coupon.length > 0) {
      if (this.data.coupon_ids.length == 0) {
        wx.showModal({
          content: '你还没有领取赠品!',
          cancelText:'放弃',confirmText	:'领取',
          success:(res)=>{
            if (res.cancel) {
              this.wechatPayment();
            }
          }
        })
      } else {
        this.wechatPayment();
      }
    }else{
      this.wechatPayment();
    }
  },
  //微信
  wechatPayment: function () {
    wx.showLoading({
      title: '支付中',
      mask: true
    })
    var parms = {
      store_id: this.data.store_id,
      user_couponr_id: this.data.coupon_user_id,
      coupon_ids: this.data.coupon_ids,
      money: this.data.input_money,
      amount: this.data.amount,
      ucode: app.globalData.ucode,
      code_id:this.data.code_id
    }
    app.api().Post('api/v4/allwin/payment/wechat',parms,(result)=>{
      app.doWechatPay(result.data,(rel) => {
        if(result.url == '/pages/index'){
          wx.switchTab({url:'../index'})
        }else{
          wx.redirectTo({url:result.url})
        }
        wx.hideLoading();
      },() => {
        wx.hideLoading();
        app.wxAlert('支付失败');
      });
    })
  },
  //不用赠品
  resestApi() {
    this.setData({
      coupon_user_id: 0,
      coupon_user_key: 0,
      discount_money:0,
    });
    this.amount() //计算价格
  },
  //键盘是否显示
  showKeyboard() {
    let input_money = parseFloat(this.data.input_money);
    if (this.data.showKeyboard){
      if (isNaN(input_money)) {
        input_money = 0;
      }
      if(input_money > 0) {
        //初始化所有赠品选择
        this.setData({
          loading: true,
          coupon: [],
          checkbox: [],
        });
        this.data.coupon_id = []
        this.data.coupon_price = 0
        this.data.page = 0
        //重新读取
        this.getStoreCoupon();
        this.getCoupon();
     }
    }else{
      if (input_money <= 0) {
        input_money = '';
      }
    }
    this.setData({
      showKeyboard:!this.data.showKeyboard,
      input_money:input_money,
    });
  },
  //虚拟键盘
  tapNum(event) {
    var keys = event.currentTarget.dataset.text,
        input_money = this.data.input_money.toString(),
        len = input_money.length;
    switch (keys) {
      case '.':
        if (len < 11 && input_money.indexOf('.') == -1) {
          if (input_money.length < 1) {
            input_money = '0.';
          } else {
            input_money += '.';
          }
        }
        break;
      case 'backspace':
        input_money = input_money.substr(0,input_money.length - 1);
        break;
    default:
      let Index = input_money.indexOf('.');
      if (Index == -1 || len - Index != 3) {
        if (len < 11) {
          input_money += keys;
        }
      }
      break
    }
    this.setData({
      input_money:input_money,
      isInput:input_money?true:false,
    });
  }
})